package com.sr.demo.security.login;

import cn.hutool.core.util.StrUtil;
import com.sr.demo.security.nuoauth.dto.NuoAuthDTO;
import com.sr.demo.security.password.NuoPasswordEncoder;
import com.sr.demo.security.user.NuoUser;
import com.sr.demo.security.user.NuoUserDetailsService;
import com.sun.xml.internal.ws.util.StringUtils;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.util.ArrayList;
import java.util.List;


/**
 * 用户登录认证类
 * @Author: liushuai
 * @Date: 2021/2/9 19:40
 * @param : * @param null
 * @return :
 **/
@Component
public class NuoAuthenticationProvider implements AuthenticationProvider {
    @Autowired
    private NuoUserDetailsService nuoUserDetailsService;
    @Autowired
    private NuoPasswordEncoder nuoPasswordEncoder;
    /**
     * 用户认证方法
     * @Author: liushuai
     * @Date: 2021/2/9 19:41
     * @param : * @param authentication
     * @return :org.springframework.security.core.Authentication
     **/
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        if(ObjectUtils.isEmpty(authentication.getPrincipal()) || ObjectUtils.isEmpty(authentication.getDetails()) || StrUtil.isBlank(authentication.getDetails().toString()) || StrUtil.isBlank(authentication.getPrincipal().toString())){
          throw  new LoginException("用户名或密码不能为空");
        }
        String userName = authentication.getPrincipal().toString();
        String password = authentication.getDetails().toString();
        NuoUser user =(NuoUser)authentication;
        if(StrUtil.isNotBlank(user.getToken())){
            return user;
        }
        user = (NuoUser) nuoUserDetailsService.loadUserByUsername(userName);

        if(user == null){
            throw  new LoginException("用户名或密码错误");
        }
        boolean isPass = nuoPasswordEncoder.matches(password, user.getPassword());
        List<NuoAuthDTO> authDTOLists = new ArrayList<>();
        if(isPass){
           //密码认证通过

        }else{
            throw  new LoginException("用户名或密码错误");
        }
        System.out.println("认证登录");
        return user;
    }
    /**
     *
     * @Author: liushuai
     * @Date: 2021/2/9 19:42
     * @param : * @param aClass
     * @return :boolean
     **/
    @Override
    public boolean supports(Class<?> aClass) {
        return aClass.equals(NuoUser.class);
    }
}
